package ${pkg};



import java.text.ParseException;
import java.util.List;
import java.util.Map;


import javax.servlet.http.HttpServletRequest;


import java.beans.IntrospectionException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.util.List;
import java.util.Map;

import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.github.miemiedev.mybatis.paginator.domain.Paginator;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.klnst.core.form.ConditionEntity;
import com.klnst.core.persistence.Criteria;
import com.klnst.core.persistence.Criterion;
import com.klnst.core.persistence.DynamicSpecifications;
import com.klnst.core.persistence.SearchFilter;
import com.klnst.core.utils.TimeUtils;
import com.klnst.domain.JgmdResult;
import com.klnst.domain.SysOperator;
import com.klnst.fts.service.EsClient;
import com.klnst.fts.service.EsResult;

import javax.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import ${daoPkg}.${clzName}Mapper;
import ${domainPkg}.${clzName};

/**
 * 
 * @ClassName: ${clzName}Service   
 * @Description: ${tableComment} 
 * @author ilaotou@qq.com
 * This class is generatored by AutoTool
 */
@Service
public class ${clzName}FulltextService {

   private static Logger logger = LoggerFactory.getLogger(${clzName}FulltextService.class);
	
	@Autowired
	public ${clzName}Mapper ${clzName?uncap_first}Mapper;
	
	@Autowired
	public EsClient esClient;
	
	
	/**
	 * 
	 * @Title: paging4elastic 
	 * @Description: 全文检索的分页方法
	 * @param filters
	 * @param pageBounds
	 * @return
	 * @throws ParseException
	 * @return List<DsjSkrkxx>    返回类型 
	 * @throws
	 */
	public List<${clzName}> paging4elastic(List<SearchFilter> filters,PageBounds pageBounds) throws ParseException{
		List<Criterion> criterions = DynamicSpecifications.bySearchFilter(filters);
		Criterion criterion = new Criterion("cj_at<",TimeUtils.getDateNow());
		criterions.add(criterion);
		Criteria criteria = new Criteria(criterions,"${tableName}");
		return ${clzName?uncap_first}Mapper.paging4elastic(criteria,pageBounds);
	}
	/**
	 * 
	 * @Title: pagingCount 
	 * @Description: 表名固定的记录总数方法
	 * @param filters
	 * @return
	 * @throws ParseException
	 * @return long    返回类型 
	 * @throws
	 */
	public long pagingCount(List<SearchFilter> filters) <#if model?exists && model="business">throws ParseException</#if>{
		List<Criterion> criterions = DynamicSpecifications.bySearchFilter(filters);
		<#if model?exists && model="business">
		Criterion criterion = new Criterion("cj_at<",TimeUtils.getDateNow());
		criterions.add(criterion);
		</#if>
		Criteria criteria = new Criteria(criterions,"${tableName}");
		return ${clzName?uncap_first}Mapper.pagingCount(criteria);
	}
	
	public void createIndex() throws IOException, ParseException{
    	
    	PageBounds pageBounds = null;
		List<SearchFilter> filters= Lists.newArrayList();
		long count = pagingCount(filters);
		logger.info("%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ${clzName}           总计：" + count);
		Paginator page = new Paginator(1,10000,(int)count);
		int totalPage = page.getTotalPages();
		logger.info("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  ${clzName}                总页数：" + totalPage);
		List indexList =null;		
		esClient.createCluterName("zhzs_fulltext_v1");
		esClient.createAliases("zhzs_fulltext_v1", "zhzs_fulltext");
		String mappingString = "{\"${tableName}\" : "
				+ "{ \"properties\" : "
				+ "{"
				+ " \"id\" : {\"type\" : \"string\", \"store\" : \"true \"}"
		        + " } "
		        + "} "
		        + "}";
		
		
	     XContentBuilder mapping = XContentFactory.jsonBuilder()
	             .startObject()
	               .startObject("${tableName}")
	               .startObject("properties")       
	                 .startObject("id").field("type", "string").field("store", "true").endObject()  
	                  <#list keyfields as prop>
	                 .startObject("${prop}").field("type", "string").field("store", "true").field("analyzer", "ik_smart").field("search_analyzer", "ik_smart").endObject()  
	                 </#list>
	               .endObject()
	              .endObject()
	            .endObject();

		esClient.createType("zhzs_yzym", "${tableName}", mapping);
		long start = System.currentTimeMillis();
		if(totalPage>0){
			for(int i=1;i<=totalPage;i++){
				List<Criterion> criterions = Lists.newArrayList();
				Criteria criteria = new Criteria(criterions,"sj_gt_djgrzz");
				pageBounds = new PageBounds(i, 10000,true);
				List<${clzName}>  _list =  ${clzName?uncap_first}Mapper.paging4elastic(criteria,pageBounds);
				indexList = Lists.newArrayList();
				BulkRequestBuilder bulkRequest = esClient.getTransportClient().prepareBulk();
				for (${clzName} entity : _list) {
					bulkRequest.add( esClient.getTransportClient().prepareIndex("zhzs_fulltext", "${tableName}")
							        .setId(entity.getId())
									.setSource(XContentFactory.jsonBuilder().startObject()
											.field("id", entity.getId())
											<#list keyfields as prop>
											.field("${prop}", entity.get${prop?cap_first}())
											</#list>
											.endObject()));

				}
				BulkResponse bulkResponse = bulkRequest.get();
				if (bulkResponse.hasFailures()) {
				    // process failures by iterating through each bulk response item
				}
			}
			long end = System.currentTimeMillis();
			long time = (end - start);
			long h=time/1000/3600;
			long m=(time/1000-h*3600)/60;
			long s=(time/1000-h*3600) % 60;
	
			logger.info(" %%%%%%%%%%%%%%%%%%%%%%%%%%%%% ${tableName}创建索引的 执行时间：" + h +"小时" + m +"分钟" + s + "秒");
		}
    }
    
    
    public EsResult<${clzName}>  pagingEs(Map<String, Object> parameters,Integer page,Integer limit) throws IllegalAccessException, InstantiationException, InvocationTargetException, IntrospectionException{
    	BoolQueryBuilder qb = QueryBuilders.boolQuery();
    	for (Map.Entry<String, Object> entry : parameters.entrySet()) {  
    	    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); 
    	    qb.should(QueryBuilders.termQuery(entry.getKey(), entry.getValue()));
    	}  
    	EsResult<${clzName}> result = esClient.pagingQuery(${clzName}.class, "zhzs_fulltext", "${tableName}", qb, null, page, limit);
    	result.setDesc("${tableComment} ");
    	result.setIndexType("${tableName}");
    	return result;
    }
    
    
	
	private static HttpServletRequest getHttpServletRequest(){
		ServletRequestAttributes sra= (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
		if(sra==null){
			return null;
		}else{
			return sra.getRequest();
		}
	}
}
